# Author:: Alexandre Ribeiro de Souza (<alexandre@lumis.com.br>)

tag('database_mysql')

::Chef::Recipe.send(:include, Opscode::OpenSSL::Password)

node.set_unless['lumis']['mysql']['root_password'] = secure_password

package "mysql-server" do
  action :install
  not_if "test -f /usr/bin/mysql_install_db"
end

service "mysql-server" do
  service_name "mysqld"
  supports :status => true, :restart => true, :reload => true
  action :enable
end

unless File.exists?(node['lumis']['mysql']['data_dir'])
  bash "Create MySQL data_dir" do
    code <<-EOH
    mkdir -p #{node['lumis']['mysql']['data_dir']}
    cp -rf /var/lib/mysql/* #{node['lumis']['mysql']['data_dir']}
    chown -R mysql:mysql #{node['lumis']['mysql']['data_dir']}
    EOH
  end
end

template "/etc/my.cnf" do
  source "my.cnf.erb"
  owner "root"
  group "root"
  mode "0644"
  notifies :restart, resources(:service => "mysql-server"), :immediately
end

execute "assign-root-password" do
  command "/usr/bin/mysqladmin -u root password \"#{node['lumis']['mysql']['root_password']}\""
  action :run
  only_if "/usr/bin/mysql -u root -e 'show databases;'"
end

grants_path = node['lumis']['mysql']['grants_path']

begin
  t = resources("template[#{grants_path}]")
rescue
  Chef::Log.info("Could not find previously defined grants.sql resource")
  t = template grants_path do
    source "grants.sql.erb"
    owner "root"
    group "root"
    mode "0600"
    action :create
  end
end

execute "Mysql Install Privileges" do
  command "/usr/bin/mysql -u root #{node['lumis']['mysql']['root_password'].empty? ? '' : '-p' }\"#{node['lumis']['mysql']['root_password']}\" < #{grants_path}"
  action :nothing
  subscribes :run, resources("template[#{grants_path}]"), :immediately
end
